package com.zjy.pet.service.impl;

import com.zjy.basic.domain.dto.ConfirmOrderDto;
import com.zjy.basic.exception.CustomException;
import com.zjy.basic.util.AjaxResult;
import com.zjy.pet.domain.OrderPetAcquisition;
import com.zjy.pet.domain.Pet;
import com.zjy.pet.domain.SearchMasterMsg;
import com.zjy.pet.mapper.OrderPetAcquisitionMapper;
import com.zjy.pet.mapper.PetMapper;
import com.zjy.pet.mapper.SearchMasterMsgMapper;
import com.zjy.pet.service.OrderPetAcquisitionService;
import com.zjy.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements OrderPetAcquisitionService {

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    /**
     * 收购成功
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult confirm(ConfirmOrderDto dto) {
        //判断订单状态是否是待处理
        OrderPetAcquisition opa = orderPetAcquisitionMapper.findById(dto.getId());
        if (opa.getState() != 0) {
            throw new CustomException("订单状态异常");
        }
        //更新宠物信息
        Pet pet = petMapper.findById(opa.getPetId());
        //更新成本价
        pet.setCostprice(dto.getMoney());
        petMapper.update(pet);
        //更新订单信息
        opa.setPaytype(dto.getPayType());
        //更新收购金额
        opa.setPrice(dto.getMoney());
        //更新收购订单状态为已完成
        opa.setState(1);
        orderPetAcquisitionMapper.update(opa);
        //更新寻主消息状态
        SearchMasterMsg msg = searchMasterMsgMapper.findById(opa.getSearchMasterMsgId());
        msg.setState(2);
        searchMasterMsgMapper.update(msg);
        return AjaxResult.me();
    }

    /**
     * 收购失败
     * @param id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult cancel(Long id) {
        //判断订单状态是否是待处理
        OrderPetAcquisition opa = orderPetAcquisitionMapper.findById(id);
        if (opa.getState() != 0) {
            throw new CustomException("订单状态异常");
        }
        //修改收购单的状态
        opa.setState(-1);
        orderPetAcquisitionMapper.update(opa);
        //删狗子
        petMapper.del(opa.getPetId());
        //置空msg的shopid
        SearchMasterMsg msg = searchMasterMsgMapper.findById(opa.getSearchMasterMsgId());
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);
        return AjaxResult.me();
    }
}
